package com.snifferx.servlet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.snifferx.managedbeans.RegisterBean;

public class UploadServlet extends HttpServlet {

	private static final long serialVersionUID = -3714619333861571457L;
	private static Logger log = Logger.getLogger(UploadServlet.class);

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		log.debug("Servlet inin ok ");
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
		response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
		response.setDateHeader("Expires", 0); // Proxies.
		
		request.setCharacterEncoding("UTF-8");
		// determine whether uploadFile is present.
		boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
		if (!isMultipartContent) {
			return;
		}
		FileItem fileItem = null;
		String name = "";
		String extName = "";
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(1024000);
			File fileDir = new File(this.getServletConfig().getServletContext().getRealPath("") + "/tmp/");
			log.debug("into this , and determine fileDir = " + this.getServletConfig().getServletContext().getRealPath("") + "/tmp/");
			if (!fileDir.exists()) {
				System.out.println("floder not exists and create new ...");
				fileDir.mkdir();
			}
			factory.setRepository(fileDir);
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			upload.setSizeMax(-1);
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				if (!item.isFormField()) {
					fileItem = item;
					name = item.getName();
					long size = item.getSize();
					String type = item.getContentType();
					System.out.println(size + " " + type);
					if (name == null || name.trim().equals("")) {
						continue;
					}
					if (name.lastIndexOf(".") >= 0) {
						extName = name.substring(name.lastIndexOf("."));
					}
					
					
					//save to tmp
					//File saveFile = new File(this.getServletConfig().getServletContext().getRealPath("") + "/tmp/" + name);
					//log.debug("tmp realpath : " + this.getServletConfig().getServletContext().getRealPath("") + "/tmp/" + name);
					//item.write(saveFile);
					
					
					
				}
			}
		} catch (Exception ex) {
			log.warn(ex.getMessage());
		}

		if (fileItem == null) {
			return;
		}
		String key = request.getParameter("key");
		getServletContext().setAttribute(key, fileItem);
		response.getWriter().print(name + extName);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		log.debug("-------DoGet----------");
	}
}